package com.zipking.cloud.springbootmybatis.redisson;
import cn.hutool.extra.spring.SpringUtil;
import com.zipking.cloud.springbootmybatis.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class RedisDelayQueueRunner  implements CommandLineRunner {
    @Autowired
    private RedissonClient redissonClient ;

    @Override
    public void run(String... args) {
        RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
        for (RedisDelayQueueEnum queueEnum : queueEnums) {
            RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueEnum.getCode());
            //避免消息伪丢失（应用重启未消费），官网推荐
            redissonClient.getDelayedQueue(blockingDeque) ;
            new Thread(() -> {
                while (true) {
                    try {
                        Object take = blockingDeque.take();
                        if(Objects.nonNull(take)) {
                            RedisDelayQueueHandle redisDelayQueueHandle = SpringUtils.getBean(queueEnum.getBeanId());
                            redisDelayQueueHandle.execute(take);
                        }
                    } catch (InterruptedException e) {
                        log.error("(Redis延迟队列异常中断) {}", e.getMessage());
                    }
                }
            }).start();
        }
        log.info("Redis延迟队列启动成功");
    }

}
